//
//  NSMutableAttributedString+USCTKern.m
//  test
//
//  Created by 余国平 on 16/8/9.
//  Copyright © 2016年 余国平. All rights reserved.
//

#import "NSMutableAttributedString+USCTKern.h"
#import<CoreText/CoreText.h>
@implementation NSMutableAttributedString (USCTKern)
- (NSMutableAttributedString *)getASMlabelWidth:(CGFloat)width labelFontValue:(CGFloat)fontValue string:(NSString *)string ignoreLength:(NSInteger)ignoreLength {
    
    /*** 防止 width 过大，引起错误 ***/
    NSLog(@"%f", kUSScreenWidth);
    NSAssert(width < kUSScreenWidth, @"当前给定的 label 宽度大于屏幕宽度");
    
    /*** 适应当只有一行且文本比较少的情况 fuck ***/
    width = width > 70 ? width : 70;
    NSMutableAttributedString *asmString = [[NSMutableAttributedString alloc] initWithString:string];
    
    /*** 计算需要有间距的 length  ***/
    NSInteger caluLength = string.length - ignoreLength;
    
    /*** 计算没有间隔情况下的文字宽度 ***/
    CGFloat stringWidth = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT)  options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontValue]} context:nil].size.width;
    
    if ([USFunction isChinese]) {
        
        
        /*** 计算有间隔字符之间的间隔 ***/
        float number = (float)(width - stringWidth) / caluLength;
        
        /*** 防止 width 过小，引起错误 ***/
        NSAssert(number >= 0, @"当前给定的 label 宽度小于字符串实际的宽度");
        
        /*** 给指定的范围添加间隔 ***/
        CFNumberRef num = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &number);
        [asmString addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0, caluLength)];
        
        CFRelease(num);
    } else {
        /*** 计算有间隔字符之间的间隔 ***/
        float number = (float)(width - stringWidth);
        
        /*** 防止 width 过小，引起错误 ***/
        NSAssert(number >= 0, @"当前给定的 label 宽度小于字符串实际的宽度");
        
        /*** 给指定的范围添加间隔 ***/
        CFNumberRef num = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &number);
        [asmString addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(string.length - 2, 1)];
        
        CFRelease(num);
        
    }
    
    
    return asmString;
}

- (NSMutableAttributedString *)getASMlabelWidth:(CGFloat)width usFontValue:(CGFloat)usValue string:(NSString *)string ignoreLength:(NSInteger)ignoreLength {
    return [self getASMlabelWidth:width labelFontValue:(0.75 * usValue) string:string ignoreLength:ignoreLength];
}

@end
